﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Configuration;

namespace Kis2012.Models
{
    public class RoleTable
    {
        private Table<Role> rolesTable;
        private DataContext context;

        public RoleTable()
        {
            string connStr = ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;
            context = new DataContext(connStr);
            rolesTable = context.GetTable<Role>();
        }

        public Role GetRoleByName(string Name)
        {
            Role role = rolesTable.SingleOrDefault(u => u.RoleName == Name);
            return role;
        }

        public IEnumerable<Role> GetAllRoles()
        {
            return rolesTable.AsEnumerable();
        }

        public int RegisterRole(string name)
        {
            Role role = new Role();
            role.RoleName = name;
            rolesTable.InsertOnSubmit(role);
            context.SubmitChanges();
            
            return role.RoleId;
        }

        public bool DeleteRole(string name)
        {
            Role role = rolesTable.SingleOrDefault(u => u.RoleName == name);
            if (role != null)
            {
                rolesTable.DeleteOnSubmit(role);
                context.SubmitChanges();
                return true;
            }
            return false;
        }

        public bool UpdateRole(string name, string newName)
        {
            Role role = rolesTable.SingleOrDefault(u => u.RoleName == name);
            if (role != null)
            {
                role.RoleName = newName;
                context.SubmitChanges();
                return true;
            }
            return false;
        }
    }
}